package com.jin.webvideo.js.stopwatch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;


public class StopwatchThread extends Thread{
    protected static final Logger logger = LoggerFactory.getLogger(StopwatchThread.class);

    private static StopwatchThread timeoutThread;

    public static StopwatchThread newIntance(){
        if (null == timeoutThread){
            synchronized (StopwatchThread.class){
                if (null == timeoutThread){
                    timeoutThread = new StopwatchThread(3000);
                    timeoutThread.start();
                }
            }
        }
        return timeoutThread;
    }

    public interface TimeoutEvent{
        void accept();
    }
    private ListIterator<TimeInfo> iterator;
    private boolean running = false;
    // 定时 扫描间隔
    private long scanInterval;

    private StopwatchThread(long scanInterval){
        this.scanInterval = scanInterval;
        iterator = new LinkedList<TimeInfo>().listIterator(0);
    }

    private StopwatchThread(){
        this(1000);
    }

    public void addTimeoutEvent(String name, long time, TimeoutEvent event){
        TimeInfo item = new TimeInfo(name, time, event);
        iterator.add(item);
        logger.debug("create new task {}", item);
    };

    @Override
    public synchronized void start() {
        running = true;
        logger.debug("StopwatchThread start scanInterva={}", this.scanInterval);
        super.start();
    }

    @Override
    public void run() {
        try{
            while (running){
                Thread.sleep(scanInterval);
                while (iterator.hasNext()) {
                    TimeInfo item = iterator.next();
                    if (item.spend()) {
                        logger.debug("execution {} is complete", item);
                        iterator.remove();
                    }
                }
            }
            logger.debug("StopwatchThread stop run");
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    public void destory(){
        running = false;
    }
}


